package cn.ssm.controller;

import cn.ssm.bean.Category;
import cn.ssm.bean.Product;
import cn.ssm.service.CategoryService;
import cn.ssm.service.ProductService;
import cn.ssm.util.PageSite;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.List;

@RequestMapping("")
@Controller
public class ProductController {
    @Autowired
    ProductService productService;
    @Autowired
    CategoryService categoryService;

    @RequestMapping(value = "products/{id}", method = RequestMethod.GET)
    public ModelAndView listProduct(PageSite pageSite, Category category){
        ModelAndView mav = new ModelAndView("listProduct");

        int pagelimit = 3;
        int cid = category.getId();
        PageHelper.offsetPage(pageSite.getStart(), pagelimit);
        List<Product> lists = productService.list(cid);
        int totalcount = (int) new PageInfo(lists).getTotal();

        pageSite.setCount(pagelimit);
        pageSite.calculateLast(totalcount);
        pageSite.calculateNum(totalcount);
        Integer[] arr = new Integer[pageSite.getNumber()];

        mav.addObject("yeshu", Arrays.asList(arr));
        mav.addObject("listProducts", lists);
        category = categoryService.get(cid);
        mav.addObject("category", category);
        return mav;
    }
}
